package shopping

import (
	"dhfshop/models/shopping"
	"encoding/json"
	"time"
	"errors"
	"strconv"
	"strings"
	"dhfshop/utils/helper"
	"dhfshop/controllers/base"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

// 打折促销管理
type ActivityController struct {
	base.BaseController
}

func (this *ActivityController) GetActivityPara()(int64,int64,map[string]string,[]string,map[string]string,int,int,error) {
	query := make(map[string]string)
	fields := []string{}
	order_by := make(map[string]string)
	offset := 0     //default is 0
	limit := 10    //default is 50
	v := struct {
	    Fields       string     `form:"fields"`
		PageSize     int        `form:"page_size"`
		PageNo       int        `form:"page_no"`
		ItemId       int64      `form:"-"`
		ItemIdStr    string     `form:"item_id"`
		SkuId        int64      `form:"-"`
		SkuIdStr     string     `form:"sku_id"`
		Query        string     `form:"query"`
		OrderBy      string     `form:"order_by"`
	}{PageSize:10, PageNo:1}     
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Range(v.PageSize,1,1000,"page_size")
	valid.Range(v.PageNo,1,1000,"page_no")
	passed, _ := valid.Valid(&v)
	if !passed {
		err := errors.New(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return v.ItemId,v.SkuId,query,fields,order_by,offset,limit,err
	}
	v.PageNo = v.PageNo - 1     //为了计算offset
    if len(v.Fields) > 2 {
	    fields = strings.Split(v.Fields, ",")
	}
	//beego.Debug("GetActivityPara Query:", v.Query)
    if len(v.Query) > 2 {
	    for _, cond := range strings.Split(v.Query, ",") {
	        kv := strings.Split(cond, ":")
	        if len(kv) != 2 {
	            err := errors.New("Error: invalid query key/value pair")
	            return v.ItemId,v.SkuId,query,fields,order_by,offset,limit,err
	        }
	        k, v := kv[0], kv[1]
	        query[k] = v
	    }
	}
    if len(v.OrderBy) > 2 {
	    for _, cond := range strings.Split(v.OrderBy, ",") {
	        kv := strings.Split(cond, ":")
	        if len(kv) != 2 {
	            err := errors.New("Error: invalid order_by key/value pair")
	            return v.ItemId,v.SkuId,query,fields,order_by,offset,limit,err
	        }
	        k, v := kv[0], kv[1]
	        order_by[k] = v
	    }
	}
	offset = v.PageNo*v.PageSize
	limit = v.PageSize
	if len(v.ItemIdStr) > 0 {
	    v.ItemId, _= strconv.ParseInt(v.ItemIdStr, 10, 64)
	}
	if len(v.SkuIdStr) > 0 {
	    v.SkuId, _= strconv.ParseInt(v.SkuIdStr, 10, 64)
	}
	return v.ItemId,v.SkuId,query,fields,order_by,offset,limit,nil
}

func (this *ActivityController) ActivitysList() {
	itemId,skuId,query,fields,order_by,offset,limit,err := this.GetActivityPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	if itemId > 0 || skuId > 0 {
	    if itemId > 0 {
		    query["item_id"] = strconv.FormatInt(itemId, 10)
		}
		if skuId > 0 {
		    query["sku_id"] = strconv.FormatInt(skuId, 10)
		}
		l, cnt, err := shopping.GetAllActivityItems(query,fields,order_by,offset,limit)
	    if err != nil {
			this.ServeError(err.Error())
			return
		}
	    r := struct {
			TotalCount   int64                     `json:"total_count"`
			ActivityItem []*shopping.ActivityItem  `json:"activity_items"`
		}{TotalCount: cnt, ActivityItem: l}
		this.Data["json"] = r
	}else{
	    l, cnt, err := shopping.GetAllActivitys(query,fields,order_by,offset,limit)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		r := struct {
			TotalCount  int64               `json:"total_count"`
			Activitys   []*shopping.Activity  `json:"activitys"`
		}{TotalCount: cnt, Activitys: l}
		this.Data["json"] = r
	}
	this.ServeJSON()
}

func (this *ActivityController) Post() {
	var v shopping.Activity
	this.ParseForm(&v)
	valid := validation.Validation{}
	//valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if v.ActivityId == 0 {    //add activity
		if len(v.StartTimeStr) > 0 {
			v.StartTime, _ = time.Parse(consts.DATETIME_FORMAT,v.StartTimeStr)
		}
		if len(v.EndTimeStr) > 0 {
			v.EndTime, _ = time.Parse(consts.DATETIME_FORMAT,v.EndTimeStr)
		}
		_, err := shopping.AddActivity(&v)
		if err != nil {
		   this.ServeError(err.Error())
			return 
		}
		if len(v.ActivityItemsJson) > 0 {
			err := json.Unmarshal([]byte(v.ActivityItemsJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.ActivityItems {
				item.PartnerId = v.PartnerId
				item.Activity = &v               // pay more attention
			    if len(item.ItemIdStr) > 0 {
				    item.ItemId, _= strconv.ParseInt(item.ItemIdStr, 10, 64)
				}
				if len(item.SkuIdStr) > 0 {
				    item.SkuId, _= strconv.ParseInt(item.SkuIdStr, 10, 64)
				}	
			}
			if err := shopping.AddMultiActivityItems(v.ActivityItems); err != nil {
				this.ServeError(err.Error())
				return
			}
		}
	}else{                                 // add activity item
		oldActivity, err := shopping.GetActivityById(v.ActivityId)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		if len(v.ActivityItemsJson) > 0 {
			err := json.Unmarshal([]byte(v.ActivityItemsJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, item := range v.ActivityItems {
				item.PartnerId = oldActivity.PartnerId
				item.Activity = oldActivity               // pay more attention
				if len(item.ItemIdStr) > 0 {
				    item.ItemId, _= strconv.ParseInt(item.ItemIdStr, 10, 64)
				}
				if len(item.SkuIdStr) > 0 {
				    item.SkuId, _= strconv.ParseInt(item.SkuIdStr, 10, 64)
				}
			}
			if err := shopping.AddMultiActivityItems(v.ActivityItems); err != nil {
				this.ServeError(err.Error())
				return
			}
		}
	}
	rsp := struct {
		ActivityId int64        `json:"activity_id"`
	    Created    time.Time    `json:"created"`
	}{ActivityId: v.ActivityId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ActivityController) Put() {
	v := shopping.Activity{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ActivityId, "activity_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if len(v.StartTimeStr) > 0 {
	    v.StartTime, _ = time.Parse(consts.DATETIME_FORMAT,v.StartTimeStr)
	}
	if len(v.EndTimeStr) > 0 {
	    v.EndTime, _ = time.Parse(consts.DATETIME_FORMAT,v.EndTimeStr)
	}
	excludeArr := []string{"activity_items"}
	updateFields, err := this.GetUpdateFields(v, "", "form", excludeArr)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err := shopping.UpdateActivityById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	if len(v.ActivityItemsJson) > 0 {
	    arrJson, err := helper.SplitJsonArr(v.ActivityItemsJson)
		if err != nil {
			this.ServeError(err.Error())
		    return
		}
		for _, str := range arrJson {
			var reqItem shopping.ActivityItem
			if err = json.Unmarshal([]byte(str), &reqItem); err != nil {
				this.ServeError(err.Error())
		        return
			}
			reqItem.Activity = &v               // pay more attention
	   	    if _, err := shopping.GetActivityItemById(reqItem.Id); err == nil{
				updateField, err := this.GetUpdateFields(reqItem, str, "json", []string{""})
				if err != nil {
					this.ServeError(err.Error())
					return
				}
			    if err := shopping.UpdateActivityItem(&reqItem, updateField...); err != nil {
		            this.ServeError(err.Error())
                    return 			
	            }
			}
	    }   
	}
	r := struct {
	    ActivityId int64       `json:"activity_id"`
	    Modified   time.Time   `json:"modified"`
	}{ActivityId:v.ActivityId, Modified:time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *ActivityController) Delete() {
    partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
	v := struct {
		PartnerId   int64    `form:"-"  valid:"Required"`
	    ActivityId  int64  `form:"activity_id" valid:"Required"`
		Id          int64  `form:"id"`
	}{PartnerId: partnerId} 
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	if v.Id > 0 {
	    if err := shopping.DeleteActivityItem(v.Id); err != nil {   
	        this.ServeError(err.Error())
		    return
	    }
	}else{
	    if err := shopping.DeleteActivity(v.ActivityId); err != nil {
			this.ServeError(err.Error())
			return
	    }
	}
	r := struct {
	    ActivityId int64       `json:"activity_id"`
	    Modified   time.Time   `json:"modified"`
	}{ActivityId:v.ActivityId, Modified:time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON() 
}

